package com.wenhai.spring.bean.definition;

import com.wenhai.xiaomage.spring.ioc.overview.dependency.domain.User;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @Author:wenhai
 * @Description: Java API 注册Bean
 * @Date:2020/3/6
 */
public class JavaApiRegisterBean {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        registerUserBeanDefinition(annotationConfigApplicationContext,"user");
        registerUserBeanDefinition(annotationConfigApplicationContext, null);
        annotationConfigApplicationContext.refresh();
        Map<String, User> beansOfType = annotationConfigApplicationContext.getBeansOfType(User.class);
        System.out.println(beansOfType);
        annotationConfigApplicationContext.close();


    }


    public static void registerUserBeanDefinition(BeanDefinitionRegistry registry, String beanName){

        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
        beanDefinitionBuilder.addPropertyValue("id",1L).addPropertyValue("username","谢文海");
        if (StringUtils.hasText(beanName)) {
            registry.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
        }else {
            BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinitionBuilder.getBeanDefinition(), registry);
        }
    }
    
    
}
